<?php
/**
* @version $Id: user.php 10002 2008-02-08 10:56:57Z willebil $
* @package Joomla
* @subpackage Users
* @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/

// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );

// Editor usertype check
$access = new stdClass();
$access->canEdit = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'all' );
$access->canEditOwn = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'own' );

require_once ( $mainframe->getPath( 'front_html' ) );

$task		= mosGetParam($_POST, 'task', '');

$id			= intval(mosGetParam($_REQUEST, 'id', 0));
$catid		= intval(mosGetParam($_REQUEST, 'catid', 0));
$cid 		= josGetArrayInts( 'cid' );

switch( $task ) {
	case 'UserDetails':
		userEdit( $option, $my->id, _UPDATE );
		break;

	case 'saveUserEdit':
		// check to see if functionality restricted for use as demo site
		if ( $_VERSION->RESTRICT == 1 ) {
			mosRedirect( 'index.php?mosmsg=Functionality Restricted' );
		} else {
			userSave( $option, $my->id );
		}
		break;

	case 'CheckIn':
		CheckIn( $my->id, $access, $option );
		break;

	case 'cancel':
		//mosRedirect( 'index.php' );
		mosRedirect( sefRelToAbs('index.php?option=com_user&task=showList'));
		break;
		
	case 'showList':
		showListProduct( $my->id, $catid );
		break;
	case 'new':
		editProduct( $my->id, 0 );
		break;
	case 'edit':
		editProduct( $my->id, $id );
		break;
	case 'editA':
		editProduct( $my->id, intval( $cid[0] ), '' );
		break;	
	case 'save':
		saveProduct( $my->id, $id);
		break;
	case 'upload':
		uploadImage( $my->id, $id );
		break;
	case 'delImage':
		delImage ( $my->id, $id );
		break;
	case 'remove':
		removeProduct ( $my->id, $cid );
		break;
	case 'publish':
		changeStatusItem( $my->id, $cid, 1);
		break;
	case 'unpublish':
		changeStatusItem( $my->id, $cid, 0);
		break;
		
	default:
		showListProduct( $my->id, $catid );
		break;
}

function userEdit( $option, $uid, $submitvalue) {
	global $database, $mainframe;
	global $mosConfig_absolute_path;

	// security check to see if link exists in a menu
	$link = 'index.php?option=com_user&task=UserDetails';
	$query = "SELECT id"
	. "\n FROM #__menu"
	. "\n WHERE link LIKE '%$link%'"
	. "\n AND published = 1"
	;
	$database->setQuery( $query );
	$exists = $database->loadResult();
	if ( !$exists ) {
		mosNotAuth();
		return;
	}

	require_once( $mosConfig_absolute_path .'/administrator/components/com_users/users.class.php' );

	if ($uid == 0) {
		mosNotAuth();
		return;
	}
	$row = new mosUser( $database );
	$row->load( (int)$uid );
	$row->orig_password = $row->password;

	$row->name = trim( $row->name );
	$row->email = trim( $row->email );
	$row->username = trim( $row->username );

	$file 	= $mainframe->getPath( 'com_xml', 'com_users' );
	$params =& new mosUserParameters( $row->params, $file, 'component' );
	
	//Load city
	$sql = "SELECT id,title FROM #__city WHERE published=1 ORDER BY title ASC, id DESC";
	$database->setQuery($sql);
	$listCity = $database->loadObjectList();
	
	//District for city
	$sql = "SELECT id,title FROM #__district WHERE published=1 AND city_id=".$row->city_id." ORDER BY title ASC, id DESC";
	$database->setQuery($sql);
	$lsDistrict = $database->loadObjectList();

	HTML_user::userEdit( $row, $option, $submitvalue, $params, $listCity, $lsDistrict );
}

function userSave( $option, $uid) {
	global $database, $my, $mosConfig_frontend_userparams;

	$user_id = intval( mosGetParam( $_POST, 'id', 0 ));

	// do some security checks
	if ($uid == 0 || $user_id == 0 || $user_id != $uid) {
		mosNotAuth();
		return;
	}

	// simple spoof check security
	josSpoofCheck();

	$row = new mosUser( $database );
	$row->load( (int)$user_id );

	$orig_password = $row->password;
	$orig_username = $row->username;

	if (!$row->bind( $_POST, 'gid usertype' )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	$row->name = trim($row->name);
	$row->email = trim($row->email);
	$row->username = trim($row->username);

	mosMakeHtmlSafe($row);

	if (isset($_POST['password']) && $_POST['password'] != '') {
		if (isset($_POST['verifyPass']) && ($_POST['verifyPass'] == $_POST['password'])) {
			$row->password = trim($row->password);
			$salt = mosMakePassword(16);
			$crypt = md5($row->password.$salt);
			$row->password = $crypt.':'.$salt;
		} else {
			echo "<script> alert(\"".addslashes( _PASS_MATCH )."\"); window.history.go(-1); </script>\n";
			exit();
		}
	} else {
		// Restore 'original password'
		$row->password = $orig_password;
	}

	if ($mosConfig_frontend_userparams == '1' || $mosConfig_frontend_userparams == 1 || $mosConfig_frontend_userparams == NULL) {
	// save params
		$params = mosGetParam( $_POST, 'params', '' );
		if (is_array( $params )) {
			$txt = array();
			foreach ( $params as $k=>$v) {
				$txt[] = "$k=$v";
			}
			$row->params = implode( "\n", $txt );
		}
	}

	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// check if username has been changed
	if ( $orig_username != $row->username ) {
		// change username value in session table
		$query = "UPDATE #__session"
		. "\n SET username = " . $database->Quote($row->username)
		. "\n WHERE username = " . $database->Quote( $orig_username )
		. "\n AND userid = " . (int) $my->id
		. "\n AND gid = " . (int) $my->gid
		. "\n AND guest = 0"
		;
		$database->setQuery( $query );
		$database->query();
	}

	mosRedirect( 'index.php?option=com_user', _USER_DETAILS_SAVE );
}

function CheckIn( $userid, $access, $option ){
	global $database;
	global $mosConfig_db;

	$nullDate = $database->getNullDate();
	if (!($access->canEdit || $access->canEditOwn || $userid > 0)) {
		mosNotAuth();
		return;
	}

	// security check to see if link exists in a menu
	$link = 'index.php?option=com_user&task=CheckIn';
	$query = "SELECT id"
	. "\n FROM #__menu"
	. "\n WHERE link LIKE '%$link%'"
	. "\n AND published = 1"
	;
	$database->setQuery( $query );
	$exists = $database->loadResult();
	if ( !$exists ) {
		mosNotAuth();
		return;
	}

	$lt = mysql_list_tables($mosConfig_db);
	$k = 0;
	echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
	while (list($tn) = mysql_fetch_array($lt)) {
		// only check in the jos_* tables
		if (strpos( $tn, $database->_table_prefix ) !== 0) {
			continue;
		}
		$lf = mysql_list_fields($mosConfig_db, "$tn");
		$nf = mysql_num_fields($lf);

		$checked_out = false;
		$editor = false;

		for ($i = 0; $i < $nf; $i++) {
			$fname = mysql_field_name($lf, $i);
			if ( $fname == "checked_out") {
				$checked_out = true;
			} else if ( $fname == "editor") {
				$editor = true;
			}
		}

		if ($checked_out) {
			if ($editor) {
				$query = "SELECT checked_out, editor"
				. "\n FROM `$tn`"
				. "\n WHERE checked_out > 0"
				. "\n AND checked_out = " . (int) $userid
				;
				$database->setQuery( $query );
			} else {
				$query = "SELECT checked_out"
				. "\n FROM `$tn`"
				. "\n WHERE checked_out > 0"
				. "\n AND checked_out = " . (int) $userid
				;
				$database->setQuery( $query );
			}
			$res = $database->query();
			$num = $database->getNumRows( $res );

			if ($editor) {
				$query = "UPDATE `$tn`"
				. "\n SET checked_out = 0, checked_out_time = " . $database->Quote( $nullDate ) . ", editor = NULL"
				. "\n WHERE checked_out > 0"
				. "\n AND checked_out = " . (int) $userid
				;
				$database->setQuery( $query );
			} else {
				$query = "UPDATE `$tn`"
				. "\n SET checked_out = 0, checked_out_time = " . $database->Quote( $nullDate )
				. "\n WHERE checked_out > 0"
				. "\n AND checked_out = " . (int) $userid
				;
				$database->setQuery( $query );
			}
			$res = $database->query();

			if ($res == 1) {

				if ($num > 0) {
					echo "\n<tr class=\"row$k\">";
					echo "\n	<td width=\"250\">";
					echo _CHECK_TABLE;
					echo " - $tn</td>";
					echo "\n	<td>";
					echo _CHECKED_IN;
					echo "<b>$num</b>";
					echo _CHECKED_IN_ITEMS;
					echo "</td>";
					echo "\n</tr>";
				}
				$k = 1 - $k;
			}
		}
	}
	?>
	<tr>
		<td colspan="2">
			<b><?php echo _CONF_CHECKED_IN; ?></b>
		</td>
	</tr>
	</table>
	<?php
}

// ADD FEATURE FOR USER
function checkUserLogin (){
	global $my;
	if (!$my || $my->id == 0){
		$message_logout = 'Phiên làm việc của bạn đã hết hiệu lực, vui lòng đăng nhập lại hệ thống để sử dụng !';
		mosRedirect( sefRelToAbs('index.php?otion=com_login&task=login'), $message_logout );
	}
}

//function show products with condition categories
function showListProduct ( $uid, $catid ){
	global $database, $mainframe;
	checkUserLogin();
	$task		= mosGetParam($_REQUEST, 'task', '');
	if ($task == 'edit'){
		editProduct($uid, $id);
	}
	
	if ($catid == 0) $title_page = 'Quản lý sản phẩm';
	else{
		$sql = "SELECT title FROM #__categories WHERE id=".$catid;
		$database->setQuery($sql);
		$database->loadObject($row);
		$title_page = 'Quản lý sản phẩm nhóm '.$row->title;
	}
	$mainframe->setPageTitle($title_page);
	
	$where  = " AND cd.user_id=".$uid;
	if ($catid)		$where .= " AND cd.catid=".$catid;
	
	$sql = "SELECT COUNT(*) FROM #__content AS cd, #__categories AS cat WHERE cd.catid=cat.id".$where;
	$database->setQuery($sql);
	$total = $database->loadResult();

	$sql = "SELECT cd.id AS id, cd.catid AS catid, cd.title AS title, cd.title_alias AS title_alias, cd.created AS created, cd.thumbnailImage AS thumbnailImage, cd.largeImage AS largeImage, cd.state AS state, cd.vip AS vip, cd.hits AS hits, "
					."cat.title AS titlecat, cat.name AS html_namecat "
			."\n FROM #__content AS cd, #__categories AS cat"
			."\n WHERE cd.catid=cat.id ".$where." ORDER BY cd.ordering ASC, cd.id DESC";
	$database->setQuery( $sql, $limitstart, $numberPage );
	$rows = $database->loadObjectlist();
	
	require_once( $GLOBALS['mosConfig_absolute_path'] . '/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $numberPage );
	$link_page = sefRelToAbs($mosConfig_live_site."/index.php?option=com_user&task=showList");
	
	HTML_user::showListProducts ( $title_page, $total, $rows, $task );
}

//function add and edit Products
function editProduct ( $uid, $id ){
	global $database, $my, $mainframe;
	global $mosConfig_absolute_path, $mosConfig_live_site, $mosConfig_offset;
	checkUserLogin();
	
	$hiddenmain		= intval(mosGetParam($_REQUEST, 'hiddenmain', 0));
	if ($hiddenmain == 1){
		$id		= intval(mosGetParam($_REQUEST, 'id', 0));
	}
	
	$mainframe->setPageTitle(_UPDATE_PRODUCT);
	
	$row = new mosContent( $database );
	$row->load( (int)$id );
	
	// get list of sections
	$sql = "SELECT id, title FROM #__sections WHERE published=1 ORDER BY ordering ASC, id DESC";
	$database->setQuery($sql);
	$lsSection = $database->loadObjectList();
	
	$sectionid		= intval(mosGetParam($_REQUEST, 'sectionid', 0));
	if ($row->id >0){
		$whereCatID 	= " AND section=".$row->sectionid;
	}else{
		$whereCatID		= " AND section=".$sectionid;
	}
	// get list of categories from sections
  	$sql = "SELECT id, title FROM #__categories WHERE published=1 ".$whereCatID." ORDER BY ordering ASC, id DESC";
	$database->setQuery($sql);
	$lsCategories = $database->loadObjectList();
	
	//get hangsx
	$sql = "SELECT id,name FROM #__catphone WHERE published=1 ORDER BY name ASC, ordering ASC";
	$database->setQuery($sql);
	$listHangsx = $database->loadObjectList();
	
	HTML_user::editProduct( $row, $lsSection, $lsCategories, $listHangsx );
}

//function save product
function saveProduct ( $uid, $id){
	global $database, $my, $mainframe, $mosConfig_offset, $mosConfig_absolute_path;
	checkUserLogin();
	
	//Get the new coordinates to crop the image.
	$x1 		= intval( mosGetParam( $_REQUEST, 'x1', 0 ) );
	$y1 		= intval( mosGetParam( $_REQUEST, 'y1', 0 ) );
	$x2 		= intval( mosGetParam( $_REQUEST, 'x2', 0 ) );
	$y2 		= intval( mosGetParam( $_REQUEST, 'y2', 0 ) );
	$w	 		= intval( mosGetParam( $_REQUEST, 'w', 0 ) );
	$h	 		= intval( mosGetParam( $_REQUEST, 'h', 0 ) );

	$nullDate 	= $database->getNullDate();
	
	$row = new mosContent( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// sanitise id field
	$row->id = (int) $row->id;
	
	if ($row->id) {
		$row->modified 		= date( 'Y-m-d H:i:s' );
		$row->modified_by 	= $my->id;
	}

	$row->created_by 	= $row->created_by ? $row->created_by : $my->id;

	if ($row->created && strlen(trim( $row->created )) <= 10) {
		$row->created 	.= ' 00:00:00';
	}
	$row->created 		= $row->created ? mosFormatDate( $row->created, '%Y-%m-%d %H:%M:%S', -$mosConfig_offset ) : date( 'Y-m-d H:i:s' );

	if (strlen(trim( $row->publish_up )) <= 10) {
		$row->publish_up .= ' 00:00:00';
 	}
	$row->publish_up = mosFormatDate( $row->publish_up, _CURRENT_SERVER_TIME_FORMAT, -$mosConfig_offset );

	if (trim( $row->publish_down ) == 'Never' || trim( $row->publish_down ) == '') {
		$row->publish_down = $nullDate;
	} else {
		if (strlen(trim( $row->publish_down )) <= 10) {
			$row->publish_down .= ' 00:00:00';
		}
		$row->publish_down = mosFormatDate( $row->publish_down, _CURRENT_SERVER_TIME_FORMAT, -$mosConfig_offset );
	}

	$row->user_id 		= $my->id;
	$row->state 		= intval( mosGetParam( $_REQUEST, 'state', 0 ) );
	/*set vip, hit = 0*/
	$row->vip	 		= 0;
	$row->hits 			= 0;

	// code cleaner for xhtml transitional compliance
	$row->introtext = str_replace( '<br>', '<br />', $row->introtext );
	$row->fulltext 	= str_replace( '<br>', '<br />', $row->fulltext );

 	// remove <br /> take being automatically added to empty fulltext
 	$length	= strlen( $row->fulltext ) < 9;
 	$search = strstr( $row->fulltext, '<br />');
 	if ( $length && $search ) {
 		$row->fulltext = NULL;
 	}

	$row->title 		= ampReplace( $row->title );
	$title_alias 		= mosGetParam($_REQUEST, 'title', '');
	$title_seo			= RemoveSign($title_alias);
	$title_seo_en		= str_replace(" ", "-", $title_seo);
	$title_seo_en		= preg_replace('/[^a-z0-9]+/i','-',$title_seo_en);
	
	$row->title_alias 	= $title_seo_en;
	
	$tietkiem 		= $row->price-$row->price_giam;
	$phan_tram 		= round(($tietkiem/$row->price)*100);
	$row->giam_gia 	= $phan_tram;
	if ($row->price > $row->price_giam){
		$row->muc_giam = $row->price-$row->price_giam;
	}else{
		$row->muc_giam = 0;
	}	

 	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}			
	
	//upload and crop image
	$uploaddir = $mosConfig_absolute_path."/uploads/content";
	$upload_path = $uploaddir;
	
	$large_image_name = $title_seo_en."_large_pic.jpg"; 		// New name of the large image
	$medium_image_name = $title_seo_en."_medium_pic.jpg"; 		// New name of the medium image
	$thumb_image_name = $title_seo_en."_thumbnail_pic.jpg"; 	// New name of the thumbnail image
	$max_file = "1148576"; 										// Approx 1MB
	$max_width = "500";											// Max width allowed for the large image
	$medium_width = "160";										// Width of medium image
	$medium_height = "160";
	$thumb_width = "80";										// Width of thumbnail image
	$thumb_height = "80";

	//Image Locations
	$large_image_location 	= $upload_path."/large/".$large_image_name;
	$medium_image_location 	= $upload_path."/medium/".$medium_image_name;
	$thumb_image_location 	= $upload_path."/thumbnail/".$thumb_image_name;
	
	//Get the file information
	$userfile_name = $_FILES['img']['name'];
	$userfile_tmp = $_FILES['img']['tmp_name'];
	$userfile_size = $_FILES['img']['size'];
	$filename = basename($_FILES['img']['name']);
	$file_ext = substr($filename, strrpos($filename, '.') + 1);
	
	//Only process if the file is a JPG and below the allowed limit
	if((!empty($_FILES["img"])) && ($_FILES['img']['error'] == 0)) {
		if (($file_ext!="jpg") && ($userfile_size > $max_file)) {
			$error= "CHỈ hình ảnh jpeg dưới 1MB được chấp nhận cho tải lên";
		}
	}else{
		$error= "Chọn một hình ảnh jpeg để tải lên";
	}
	
	if($row->id==0){
		if (copy ( $mosConfig_absolute_path."/uploads/temp/temp_pic.jpg", $uploaddir."/large/".$large_image_name)){
			@unlink($mosConfig_absolute_path."/uploads/temp/temp_pic.jpg");
			$row->largeImage = $large_image_name;
		}
		//Scale the image to the medium_width set above
		$scale = $medium_width/$w;
		$cropped = resizeThumbnailImage($medium_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
		$row->mediumImage = $medium_image_name;
		if (copy ( $medium_image_location, $thumb_image_location)){
			$row->thumbnailImage = $thumb_image_name;
			Resize_File($row->thumbnailImage, $upload_path."/thumbnail/", $thumb_width, $thumb_height);
		}
	}else{
		if (copy ( $mosConfig_absolute_path."/uploads/temp/temp_pic.jpg", $uploaddir."/large/".$large_image_name)){
			@unlink($mosConfig_absolute_path."/uploads/temp/temp_pic.jpg");
			$row->largeImage = $large_image_name;
		}
		//Scale the image to the medium_width set above
		$scale = $medium_width/$w;
		$cropped = resizeThumbnailImage($medium_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
		$row->mediumImage = $medium_image_name;
		if (copy ( $medium_image_location, $thumb_image_location)){
			$row->thumbnailImage = $thumb_image_name;
			Resize_File($row->thumbnailImage, $upload_path."/thumbnail/", $thumb_width, $thumb_height);
		}
	}
	
	$row->version++;
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	mosRedirect( sefRelToAbs('index.php?option=com_user&task=showList'));
}

//upload image
function uploadImage( $uid, $id ){
	global $database, $my, $mainframe, $mosConfig_offset, $mosConfig_absolute_path;
	checkUserLogin();
	
	$task			= mosGetParam($_POST, 'task', '');
	$title			= mosGetParam($_POST, 'title', '');
	$sectionid		= intval(mosGetParam($_POST, 'sectionid', 0));
	$catid			= intval(mosGetParam($_POST, 'catid', 0));
	$add_link 		= "&title=".$title."&sectionid=".$sectionid."&catid=".$catid;
	
	$userfile_name = $_FILES['image']['name'];
	$userfile_tmp = $_FILES['image']['tmp_name'];
	$userfile_size = $_FILES['image']['size'];
	$filename = basename($_FILES['image']['name']);
	$file_ext = substr($filename, strrpos($filename, '.') + 1);
	
	//Only process if the file is a JPG and below the allowed limit
	if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
		if (($file_ext!="jpg") && ($userfile_size > $max_file)) {
			$msg= "Chỉ ảnh jpeg dưới 1MB mới được chấp nhận cho tải lên !";
		}
	}else{
		$msg= "Select a jpeg image for upload";
	}
	
	$large_image_name = 'temp_pic';
	$uploaddir = $mosConfig_absolute_path."/uploads/temp/";
	
	if (strlen($msg)==0){
		$upload = $uploaddir . basename(get_new_file_name($_FILES['image']['name'],$large_image_name.""));		  					
		if (move_uploaded_file($_FILES['image']['tmp_name'], $upload)) {
			$msg = 'Upload ảnh thành công !';					
		}else{
			$msg = 'Upload ảnh lỗi, hãy thử lại !';
		}
	}
	
	//$msg = 'Uploads Successfully !';
	mosRedirect( sefRelToAbs('index.php?option=com_user&task=edit&hiddenmain=1&id='.$id.$add_link), $msg);
}

//del Image
function delImage( $uid, $id ){
	global $database, $my, $mainframe, $mosConfig_offset, $mosConfig_absolute_path, $mosConfig_dbprefix;
	checkUserLogin();
	
	$path = $mosConfig_absolute_path."/uploads/content";
	
	$sql = "SELECT largeImage,mediumImage,thumbnailImage FROM #__content WHERE id=".$id;
	$database->setQuery($sql);
	$database->loadObject($row);
	
	if ($row->largeImage!=''){
		$update = "UPDATE ".$mosConfig_dbprefix."content"
				."\n SET largeImage='',"
				."\n mediumImage='',"
				."\n thumbnailImage=''"
				."\n WHERE id=".$id
				;
		if (mysql_query($update)){
			@unlink($path."/large/".$row->largeImage);
			@unlink($path."/medium/".$row->mediumImage);
			@unlink($path."/thumbnail/".$row->thumbnailImage);
			$msg = 'Ảnh đã được xóa khỏi sản phẩm !';
		}else{
			$msg = 'Có lỗi xảy ra trong quá trình xóa ảnh sản phẩm, vui lòng thử lại !';
		}		
	}
	mosRedirect( sefRelToAbs('index.php?option=com_user&task=edit&hiddenmain=1&id='.$id.$add_link), $msg);
}

//function published item
function changeStatusItem ( $uid, $cid=null, $state=0 ){
	global $database, $my;
	checkUserLogin();
	//var_dump($my); die;

	josSpoofCheck();

	if (count( $cid ) < 1) {
		$action = $state == 1 ? 'publish' : ($state == -1 ? 'archive' : 'unpublish');
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	mosArrayToInts( $cid );
	$total = count ( $cid );
	$cids = 'id=' . implode( ' OR id=', $cid );

	$query = "UPDATE #__content"
	. "\n SET state = " . (int) $state . ", modified = " . $database->Quote( date( 'Y-m-d H:i:s' ) )
	. "\n WHERE ( $cids ) AND ( checked_out = 0 OR (checked_out = " . (int) $my->id . ") )"
	;
	$database->setQuery( $query );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (count( $cid ) == 1) {
		$row = new mosContent( $database );
		$row->checkin( $cid[0] );
	}

	// clean any existing cache files
	mosCache::cleanCache( 'com_content' );

	switch ( $state ) {
		case -1:
			$msg = $total .' Item(s) successfully Archived';
			break;

		case 1:
			$msg = $total .' sản phẩm được hiển thị thành công !';
			break;

		case 0:
		default:
			if ( $task == 'unarchive' ) {
				$msg = $total .' sản phẩm được hiển thị thành công !';
			} else {
				$msg = $total .' sản phẩm được khóa thành công !';
			}
			break;
	}

	$redirect 	= mosGetParam( $_POST, 'redirect', $row->sectionid );
	$rtask 		= strval( mosGetParam( $_POST, 'returntask', '' ) );
	if ( $rtask ) {
		$rtask = '&task='. $rtask;
	} else {
		$rtask = '';
	}

	//mosRedirect( 'index2.php?option='. $option . $rtask .'&sectionid='. $redirect .'&mosmsg='. $msg );
	mosRedirect( sefRelToAbs('index.php?option=com_user&task=showList'), $msg);
}

//function remove Product
function removeProduct ( $uid, $cid ){
	global $database, $mosConfig_absolute_path, $my;
	checkUserLogin();
	
	$path = $mosConfig_absolute_path."/uploads/content";

	josSpoofCheck();

	$total = count( $cid );
	if ( $total < 1) {
		echo "<script> alert('Lựa chọn các sản phẩm cần xóa !'); window.history.go(-1);</script>\n";
		exit;
	}

	//seperate contentids
	mosArrayToInts( $cid );
	$cids = 'id=' . implode( ' OR id=', $cid );
	
	$sql = "SELECT * FROM #__content WHERE ( $cids )";
	$database->setQuery($sql);
	$lsImage = $database->loadObjectList();
	for ($i=0; $i<count($lsImage); $i++){
		echo $lsImage[$i]->largeImage;
		if(file_exists($path."/large/".$lsImage[$i]->largeImage)) {
		   @unlink($path."/large/".$lsImage[$i]->largeImage);
		}
		if(file_exists($path."/medium/".$lsImage[$i]->mediumImage)) {
		   @unlink($path."/medium/".$lsImage[$i]->mediumImage);
		}
		if(file_exists($path."/thumbnail/".$lsImage[$i]->thumbnailImage)) {
		   @unlink($path."/thumbnail/".$lsImage[$i]->thumbnailImage);
		}
	}
	
	$query = "DELETE FROM #__content"
	. "\n WHERE ( $cids )"
	;
	$database->setQuery( $query );
	if ( !$database->query() ) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// clean any existing cache files
	mosCache::cleanCache( 'com_content' );

	$msg 	= $total ." sản phẩm đã được xóa !";
	$return = strval( mosGetParam( $_POST, 'returntask', '' ) );
	mosRedirect( 'index2.php?option='. $option .'&task='. $return .'&sectionid='. $sectionid, $msg );
}

?>